package com.fjh.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.fjh.domain.BusCustomer;
import com.fjh.dto.CustomDto;
import com.fjh.mapper.BusCustomerMapper;
import com.fjh.service.CustomService;
import com.fjh.vo.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CustomServiceImpl implements CustomService {
    @Autowired
    private BusCustomerMapper customerMapper;

    /**
     * 分页查询
     *
     * @param customDto
     * @return
     */
    @Override
    public PageInfo<BusCustomer> findByPage(CustomDto customDto) {
        Page<Object> pageInfo = PageHelper.startPage(customDto.getPage(), customDto.getLimit());
        List<BusCustomer> busCars = customerMapper.selectList(customDto);
        return new PageInfo<>(pageInfo.getTotal(), busCars);
    }

    /**
     * 新增数据
     *
     * @param customDto
     * @return
     */
    @Override
    public Boolean save(CustomDto customDto) {
        // 1 校验
        validate(customDto);
        // 2 属性copy
        BusCustomer busCustomer = new BusCustomer();
        BeanUtils.copyProperties(customDto, busCustomer);
        // 3 填充默认的字段
        busCustomer.setCreateTime(new Date());
        return customerMapper.insert(busCustomer) > 0;
    }

    private void validate(CustomDto customDto) {
        if (customDto.getIdCard() == null) {
            throw new IllegalArgumentException("身份证号不能为空");
        }
        if (customDto.getPhone() == null) {
            throw new IllegalArgumentException("手机不能为空");
        }
    }

    /**
     * 修改数据
     *
     * @param customDto
     * @return
     */
    @Override
    public Boolean updateById(CustomDto customDto) {
        if (customDto.getId() == null) {
            throw new IllegalArgumentException("id不能为空");
        }
        // 1 校验
        validate(customDto);
        // 2 属性copy
        BusCustomer busCustomer = new BusCustomer();
        BeanUtils.copyProperties(customDto, busCustomer);
        return customerMapper.updateByPrimaryKeySelective(busCustomer) > 0;
    }

    /**
     * 删除数据
     *
     * @param ids
     * @return
     */
    @Override
    public Boolean batchDelete(Integer[] ids) {
        int row = customerMapper.batchDelete(ids);
        return row == ids.length;
    }
}
